import { Controller } from 'egg';
import * as moment from 'moment';
export default class HomeController extends Controller {
  public async create() {
    const { ctx } = this;
    const { name, phone, scope, profession, avatar, userId } = ctx.request.body;
    if (!(name && phone && scope && profession)) {
      ctx.body = { status: -1, message: '信息不完整' };
    } else {
      try {
        const lastData = await ctx.model.YoungCard.findOne({}, { cardId: -1 }).sort({ applyDate: -1 });
        await (new ctx.model.YoungCard({
          name,
          phone,
          scope,
          profession,
          avatar,
          userId,
          cardId: +(lastData ? lastData.cardId : 0) + 1,
          applyDate: moment().toDate(),
        })).save();
        ctx.body = { status: 0, message: '保存成功' };
      } catch (e) {
        ctx.body = { status: -2, message: e };
      }
    }
  }
  public async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { name, phone, scope, profession, avatar, cardId, status } = ctx.request.body;
    if (!(name && phone && scope && profession)) {
      ctx.body = { status: -1, message: '信息不完整' };
    } else {
      try {
        await ctx.model.YoungCard.updateOne({ _id: id }, {
          name,
          phone,
          scope,
          profession,
          avatar,
          status,
          cardId,
        });
        ctx.body = { status: 0, message: '保存成功' };
      } catch (e) {
        ctx.body = { status: -2, message: e };
      }
    }
  }
  public async getOpenId() {
    const { ctx } = this;
    const { code } = ctx.request.query;
    const wxUrl =
      (appId, secret, js_code) =>
        `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`;
    const appId = 'wx22df53b9fcc6f511';
    const secret = 'b325f42fae88bfc161f7bfae9f710139';
    const wxRes = (await this.ctx.curl(wxUrl(appId, secret, code), { dataType: 'json' })).data;
    try {
      const userId = wxRes.openid;
      if (!userId) {
        throw new Error('用户不存在');
      }
      ctx.body = { userId };
    } catch (e) {
      ctx.body = { status: -1, message: '用户不存在' };
    }
  }

  public async getYoungCard() {
    const { ctx } = this;
    const { userId } = ctx.request.query;
    try {
      let data = await ctx.model.YoungCard.findOne({ userId });
      if (data) {
        data = data.toJSON();
        if (data.cardId.length < 4) {
          data.cardId = Array(4 - data.cardId.length).fill('0').join('') + data.cardId;
        }
        ctx.body = data;
      } else {
        ctx.body = { userId };
      }
    } catch (e) {
      ctx.body = { status: -1, message: '用户不存在' };
    }
  }

  public async getYoungCardByStatus() {
    const { ctx } = this;
    const { status } = ctx.request.query;
    try {
      let statusParam = {}
      if (status == '0') {
        statusParam = { status: 0 };
      } else {
        statusParam = { $or: [{ status: 1 }, { status: 2 }] };
      }
      const data = await ctx.model.YoungCard.find(statusParam).sort({ applyDate: -1 });
      ctx.body = data;
    } catch (e) {
      ctx.body = { status: -1, message: '获取失败' };
    }
  }
  public async updateYoungCard() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { status } = ctx.request.body;
    try {
      await ctx.model.YoungCard.updateOne({ _id: id }, { status, updateDate: moment().toDate() });
      const data = await ctx.model.YoungCard.find({ status: 0 });
      ctx.body = data;
    } catch (e) {
      ctx.body = { status: -1, message: '更新失败' };
    }
  }

  public async deleteYoungCard() {
    const { ctx } = this;
    const { id } = ctx.params;
    try {
      await ctx.model.YoungCard.deleteOne({ _id: id });
      const data = await ctx.model.YoungCard.find({ $or: [{ status: 1 }, { status: 2 }] }).sort({ applyDate: -1 });
      ctx.body = data;
    } catch (e) {
      ctx.body = { status: -1, message: '删除失败' };
    }
  }
}
